//
//  BrokerAddVc.m
//  WGFGlobalHouses
//
//  Created by welldone on 15/5/21.
//  Copyright (c) 2015年 waiguofang. All rights reserved.
//  门店下添加经纪人

#import "BrokerAddVc.h"
#import "BdTV.h"
#import "config.h"
#import "MBProgressHUD+MJ.h"
#import "BrokerDM.h"
#import "SelecteStoreVc.h"
#import "AddStoreVc.h"

#import "LoginDataMange.h"
#import "StringTool.h"
#import "AddBrokerModel.h"
#import "UserModal.h"
#import "NSString+category.h"
#import "Tools.h"
#import "UIView+circular.h"




@interface BrokerAddVc ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIButton *companyBtn;
@property (weak, nonatomic) IBOutlet UIButton *addCompanyBtn;
@property (weak, nonatomic) IBOutlet UITextField *nameEt;
@property (weak, nonatomic) IBOutlet UITextField *mobileEt;
@property (weak, nonatomic) IBOutlet UITextField *codeEt;
@property (weak, nonatomic) IBOutlet UITextField *codeAgainEt;


@property (weak, nonatomic) IBOutlet UIButton *getYzBtn;

@property (weak, nonatomic) IBOutlet UITextField *yanZhenMaEt;


@property (weak, nonatomic) IBOutlet UIButton *saveBtn;

@property (strong,nonatomic)LoginDataMange *dataMange;
@property (strong,nonatomic)AddBrokerModel *model;

@property (weak, nonatomic) IBOutlet UIView *mainView;
@property(copy, nonatomic)NSString *storeCode;//绑定门店的code
@end

@implementation BrokerAddVc
@synthesize dataMange;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initView];
}




-(void)initView{
    [super initView];
    
    [self.saveBtn viewToCircular];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self.addCompanyBtn setAttributedTitle:[NSString makeLineStyle:@"添加" color:UIColorFromRGB(0xdb2a2b ) fontSize:14.0] forState:UIControlStateNormal];
    BdTV *title = [[BdTV alloc]initWithFrame:CGRectMake(0, 0, PMW, 44)];
    [title.backBtn setTag:11];
    [title.backBtn addTarget:self action:@selector(btnOnclick:) forControlEvents:UIControlEventTouchUpInside];
    [[title doneBtn] removeFromSuperview];
    [title setMianTitle:@"添加经纪人帐号"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:title];

    
    
    self.companyBtn.layer.borderColor = UIColorFromRGB(0xe3e3e3).CGColor;
    self.companyBtn.layer.borderWidth= 1;
    self.companyBtn.layer.cornerRadius = 6;
    [self.companyBtn.layer setMasksToBounds:true];
    
    self.getYzBtn.layer.borderColor = UIColorFromRGB(0xe3e3e3).CGColor;
    self.getYzBtn.layer.borderWidth= 1;
    self.getYzBtn.layer.cornerRadius = 6;
    [self.getYzBtn.layer setMasksToBounds:true];
    
    self.nameEt.layer.borderColor = UIColorFromRGB(0xe3e3e3).CGColor;
    self.nameEt.layer.borderWidth= 1;
    self.nameEt.layer.cornerRadius = 6;
    self.nameEt.delegate = self;
    
    
    self.mobileEt.layer.borderColor = UIColorFromRGB(0xe3e3e3).CGColor;
    self.mobileEt.layer.borderWidth= 1;
    self.mobileEt.layer.cornerRadius = 6;
    self.mobileEt.delegate = self;
    
    self.yanZhenMaEt.layer.borderColor = UIColorFromRGB(0xe3e3e3).CGColor;
    self.yanZhenMaEt.layer.borderWidth= 1;
    self.yanZhenMaEt.layer.cornerRadius = 6;
    self.yanZhenMaEt.delegate = self;
    
    self.codeEt.layer.borderColor = UIColorFromRGB(0xe3e3e3).CGColor;
    self.codeEt.layer.borderWidth= 1;
    self.codeEt.layer.cornerRadius = 6;
    self.codeEt.delegate = self;
    
    self.codeAgainEt.layer.borderColor = UIColorFromRGB(0xe3e3e3).CGColor;
    self.codeAgainEt.layer.borderWidth= 1;
    self.codeAgainEt.layer.cornerRadius = 6;
    self.codeAgainEt.delegate =self;
    
    {
        UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 1)];
        [self.nameEt setLeftViewMode:UITextFieldViewModeAlways];
        [self.nameEt setLeftView:leftView];
    }
    
    {
        UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 1)];
        [self.mobileEt setLeftViewMode:UITextFieldViewModeAlways];
        [self.mobileEt setLeftView:leftView];
    }
    
    {
        UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 1)];
        [self.codeEt setLeftViewMode:UITextFieldViewModeAlways];
        [self.codeEt setLeftView:leftView];
    }
    
    {
        UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 1)];
        [self.codeAgainEt setLeftViewMode:UITextFieldViewModeAlways];
        [self.codeAgainEt setLeftView:leftView];
    }
    {
        UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 1)];
        [self.yanZhenMaEt setLeftViewMode:UITextFieldViewModeAlways];
        [self.yanZhenMaEt setLeftView:leftView];
    
    }
    
    
    dataMange = [[LoginDataMange alloc]init];
}



-(void)btnOnclick:(UIButton*)sender{
    
    if(sender.tag==11){
        [self.navigationController popViewControllerAnimated:YES];
    }

}


- (IBAction)companyBtn:(id)sender {
    
    __weak typeof(self) baseSelf = self;
    SelecteStoreVc *selecteStoreVc = [[SelecteStoreVc alloc]initWithBlock:^(NearbyCellData *data) {
        
        [baseSelf.companyBtn setTitle:data.title forState:UIControlStateNormal];
        baseSelf.storeCode = data.detail;
    }];
    
    selecteStoreVc.selectedFlag = self.companyBtn.titleLabel.text;
    selecteStoreVc.vcType = BrokerAddVcType;
    selecteStoreVc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:selecteStoreVc animated:YES];
    
}



- (IBAction)addCompanyBtnOnClick:(id)sender {
    AddStoreVc *vc = [AddStoreVc new];
    vc.lastvcType = isOtherVC;
     vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark 获取验证码
- (IBAction)getYZMonClick:(id)sender {
    
    
    if ([self checkMobile]) {
        
        [self Countdown];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            ResulteMod *mod = [dataMange captchaWithMobile:self.mobileEt.text];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (mod.resltState == ResultFail) {
                    
                    [MBProgressHUD showError:mod.resultTip];
                }else if (mod.resltState == ResultNetError)
                {
                    [MBProgressHUD showError:@"网络错误"];
                }else
                {
                    [MBProgressHUD showSuccess:@"验证码已发送，注意查收"];
                }
                
            });
        });

        
    }
    
}

#pragma mark 校验手机号码
-(BOOL)checkMobile
{
    if ([StringTool isBlankString:self.mobileEt.text]) {
        [MBProgressHUD showError:@"请输入手机号"];
        return NO;
    }else
    {
        if (![self validateMobile:self.mobileEt.text]) {
            
            [MBProgressHUD showError:@"请输入正确的手机号"];
        }
        return  [self validateMobile:self.mobileEt.text] == NO?NO:YES;
    }
}

#pragma mark  保存信息
- (IBAction)saveBtnOnClick:(id)sender {
    
    if ([self checkInfo]) {
        
        [MBProgressHUD showMessage:@"请稍等" toView:self.view];
        __weak typeof(self)bself = self;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            BrokerDM *dm = [[BrokerDM alloc]init];
            ResulteMod *mod = [dm createbrokerWithAddBrokerModel:bself.model];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUDForView:bself.view animated:YES];
                [bself.navigationController popViewControllerAnimated:YES];
                
                if (mod.resltState == ResultFail) {
                    [MBProgressHUD showError:mod.resultTip];
                }else if (mod.resltState == ResultNetError)
                {
                    [MBProgressHUD showError:@"网络错误"];
                }else
                {
                    [MBProgressHUD showSuccess:@"添加成功"];
                }
            });
        });
    }
}

#pragma mark  检查输入的内容的是不是为空
-(BOOL)checkInfo
{
    if ([StringTool isBlankString:self.nameEt.text]) {
        [MBProgressHUD showError:@"请输入经纪人姓名"];
        return NO;
    }else if (![self checkMobile])
    {
        return NO;
    }else if ([StringTool isBlankString:self.yanZhenMaEt.text])
    {
        [MBProgressHUD showError:@"请输入验证码"];
        return NO;
    }else if (![self checkPwd])
    {
        return NO;
    }
    
    self.model = [[AddBrokerModel alloc]init];
    
    self.model.name = self.nameEt.text;
    self.model.mobile = self.mobileEt.text;
    self.model.captha = self.yanZhenMaEt.text;
    self.model.password = self.codeEt.text;
    self.model.repassword = self.codeAgainEt.text;
    
    if (![StringTool isBlankString:self.storeCode]) {
        self.model.parentCode = self.storeCode;
    }else
    {
        self.model.parentCode = [UserModal shareUserModel].userCode;
    }
    
    return YES;
}

#pragma mark  校验密码
-(BOOL)checkPwd
{
    if ([StringTool isBlankString:self.codeEt.text]) {
        [MBProgressHUD showError:@"请输入密码"];
        return NO;
    }else if ([StringTool isBlankString:self.codeAgainEt.text])
    {
        [MBProgressHUD showError:@"请再次输入密码"];
        return NO;
    }else if (![self.codeEt.text isEqualToString:self.codeAgainEt.text])
    {
        [MBProgressHUD showError:@"两次密码输入不一致"];
        return NO;
    }
    return YES;
}

#pragma mark textField的代理
- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
    CGRect dd = textField.frame;
    
    int tvbotY = dd.size.height+dd.origin.y;
    int mid  = PMH-[UserModal shareUserModel].keyboardHeight-tvbotY -64;
    
    if (mid<0) {
        
        const float movementDuration = 0.3f;
        [UIView beginAnimations: nil context: nil];
        [UIView setAnimationBeginsFromCurrentState: YES];
        [UIView setAnimationDuration: movementDuration];
        
        CGRect buf = self.view.frame;
        buf.origin.y = up ? mid : 0;
        [self.mainView setFrame:buf];
        
        [UIView commitAnimations];
    }else if(up==false){
        
        [self viewRest];
    }
}

-(void)viewRest{
    
    
    const float movementDuration = 0.3f;
    [UIView beginAnimations: nil context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    
    CGRect buf = self.mainView.frame;
    buf.origin.y =  0;
    [self.mainView setFrame:buf];
    
    [UIView commitAnimations];
}

#pragma et delegare
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self animateTextField: textField up: YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    [self animateTextField:textField up:false];
    
    [textField resignFirstResponder];
    
    [self viewRest];
    return  YES;
}
#pragma mark 验证码倒计时
-(void)Countdown
{
    __block NSInteger timeout = 60;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        if (timeout <=0) {
            dispatch_source_cancel(timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.getYzBtn setTitle:[NSString stringWithFormat:@"获取验证码"] forState:UIControlStateNormal];
                self.getYzBtn.enabled = YES;
            });
            
        }else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.getYzBtn setTitle:[NSString stringWithFormat:@"%zd重新获取",timeout] forState:UIControlStateNormal];
                self.getYzBtn.enabled = NO;
                
            });
            timeout--;
        }
    });
    dispatch_resume(timer);
}






@end
